package com.example.web.service.impl;

import com.example.web.entity.Role;
import com.example.web.mapper.RoleMapper;
import com.example.web.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> getAllRoles() {
        return roleMapper.selectAllRoles();
    }

    @Override
    public Role getRoleById(Long id) {
        return roleMapper.selectRoleById(id);
    }

    @Override
    public Role getRoleByCode(String roleCode) {
        return roleMapper.selectRoleByCode(roleCode);
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    public int addRole(Role role) {
        return roleMapper.insertRole(role);
    }

    @Override
    public int updateRole(Role role) {
        return roleMapper.updateRole(role);
    }

    @Override
    public int deleteRoleById(Long id) {
        // 先删除角色菜单关联
        roleMapper.deleteRoleMenuByRoleId(id);
        // 再删除角色
        return roleMapper.deleteRoleById(id);
    }

    @Override
    public int deleteRoleByIds(Long[] ids) {
        // 先删除角色菜单关联
        for (Long id : ids) {
            roleMapper.deleteRoleMenuByRoleId(id);
        }
        // 再删除角色
        return roleMapper.deleteRoleByIds(ids);
    }

    @Override
    @Transactional
    public int assignMenus(Long roleId, Long[] menuIds) {
        // 先删除原有的角色菜单关联
        roleMapper.deleteRoleMenuByRoleId(roleId);
        
        // 添加新的角色菜单关联
        int rows = 0;
        for (Long menuId : menuIds) {
            rows += roleMapper.insertRoleMenu(roleId, menuId);
        }
        
        return rows;
    }
}